package com.mimosa.common.web;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 限制系统在指定时间以前可用
 * 
 * @filename LimitByDateTimeFilter.java
 * @datetime 2014-5-6 下午1:24:59
 * @author ggeagle
 * 
 */
public class LimitByDateTimeFilter implements Filter {
	/**
	 * 日志记录器
	 */
	final Logger logger = LoggerFactory.getLogger(this.getClass());
	/**
	 * 限制的日期时间
	 */
	private long limitDateTime;
	static final String LIMIT = "/limit";

	@Override
	public void destroy() {
		this.limitDateTime = 0;
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;

		String path = request.getServletPath();
		if (StringUtils.contains(path, LIMIT)) {
			filterChain.doFilter(arg0, arg1);
		} else {
			long currentTime = System.currentTimeMillis();
			if (currentTime < this.limitDateTime) {
				filterChain.doFilter(arg0, arg1);
			} else {
				HttpServletResponse response = (HttpServletResponse) arg1;
				response.sendRedirect(request.getContextPath()
						+ "/limit/index.action");
			}
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String dateTimeStr = filterConfig.getInitParameter("limitTime");
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date dateTime = dateFormat.parse(dateTimeStr);
			this.limitDateTime = dateTime.getTime();
		} catch (ParseException e) {
			logger.error("invalid DateTime string : {} ", dateTimeStr);
			logger.error("error occured where get DateTimeStr info : ", e);
		}
	}
}